//
//  CustomTableView.m
//  moon
//
//  Created by beyself on 16/7/13.
//  Copyright © 2016年 beyself. All rights reserved.
//
#import "Utils.h"
#import "CustomTableView.h"

#import "UIImageView+AFNetworking.h"
#import "UIButton+AFNetworking.h"
#import "MJRefresh.h"
#import "CreateViewController.h"
#import "MateInfoViewController.h"
#import "AFHTTPSessionManager.h"
#import "ImageShowViewController.h"

@implementation CustomTableView

- (id) init:(int)tab
{
    self = [super init];
    _mTab = tab;
    
    _mArray = [[NSMutableArray alloc] init];
    _mHeightDic = [[NSMutableDictionary alloc] init];
    
    UIView* tip = [[UIView alloc] init];
    tip.frame = CGRectMake(0, 0, SCREEN_WIDTH, 110);
    tip.center = CGPointMake(SCREEN_WIDTH/2, (SCREEN_HEIGHT - 49)/2);
    tip.hidden = YES;
    tip.tag = 369;
    [self addSubview:tip];
    
    UILabel* label = [[UILabel alloc] init];
    label.frame = CGRectMake(0, 0, SCREEN_WIDTH, 20);
    label.text = @"当前栏目暂时没有信息哦";
    label.textColor = BLUE;
    label.font = FONT_15;
    label.textAlignment = NSTextAlignmentCenter;
    [tip addSubview:label];
    
    UIImageView* img = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ic_tip"]];
    img.frame = CGRectMake((SCREEN_WIDTH-80)/2, 30, 80, 80);
    [tip addSubview:img];
    
    self.backgroundColor = [UIColor clearColor];
    self.showsVerticalScrollIndicator = NO;
    self.showsHorizontalScrollIndicator = NO;
    self.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 49 - 32);
    self.delegate = self;
    self.dataSource = self;
    self.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.allowsSelection = NO;
    self.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _mGetMore = 0;
        [self viewWithTag:369].hidden = YES;
        
        NSMutableDictionary* param = [[NSMutableDictionary alloc] init];
        [param setValue:APPDELEGATE.mMemberInfo[@"id"] forKey:@"id"];
        
        if(_mTab == 0)
        {
            [param setValue:[APPDELEGATE.mMainViewController.mSelectClass componentsJoinedByString:@","] forKey:@"class_id"];
            [param setValue:@"4" forKey:@"type"];
        }
        else if(_mTab == 1)
        {
            NSArray* array = [self filterExpire:APPDELEGATE.mMainViewController.mSelectClass];
            //            [param setValue:[array componentsJoinedByString:@","] forKey:@"class_id"];
            [param setValue:[APPDELEGATE.mMainViewController.mSelectClass componentsJoinedByString:@","] forKey:@"class_id"];
            [param setValue:@"1" forKey:@"type"];
        }
        else if(_mTab == 2)
        {
            NSArray* array = [self filterExpire:APPDELEGATE.mMainViewController.mSelectClass];
            //            [param setValue:[array componentsJoinedByString:@","] forKey:@"class_id"];
            [param setValue:[APPDELEGATE.mMainViewController.mSelectClass componentsJoinedByString:@","] forKey:@"class_id"];
            [param setValue:@"2" forKey:@"type"];
        }
        else if(_mTab == 3)
        {
            NSArray* array = [self filterExpire:APPDELEGATE.mMainViewController.mSelectClass];
//            [param setValue:[array componentsJoinedByString:@","] forKey:@"student_id"];
            [param setValue:[APPDELEGATE.mMainViewController.mSelectClass componentsJoinedByString:@","] forKey:@"class_id"];
            [param setValue:@"5" forKey:@"type"];
        }
        
        int count = (int)_mArray.count;
        if(_mGetMore == 1)
        {
            [param setValue:[NSNumber numberWithInt:count] forKey:@"start"];
            [param setValue:[NSNumber numberWithInt:10] forKey:@"perpage"];
        }
        else
        {
            int count = (int)_mArray.count;
            if(count < 10) count = 10;
            
            [param setValue:@"0" forKey:@"start"];
            [param setValue:[NSNumber numberWithInt:count] forKey:@"perpage"];
        }
        
        [self sendHttpPostNOWait:param method:@"get_post_list" flag:_mTab];
    }];
    
    self.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        _mGetMore = 1;
        [self sendHttpPost];
    }];
    self.tableFooterView = [[UIView alloc] init];
    
    
    return self;
}

- (void) httpCallbackFail:(int)flag
{    
    [self.mj_header endRefreshing];
    [self.mj_footer endRefreshing];
}

- (void) removeSelf
{
    [_inputView removeFromSuperview];
}

- (void) showCommentDialog
{
    _inputView = [[UIControl alloc] init];
    _inputView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    _inputView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:.3];
    [_inputView addTarget:self action:@selector(removeSelf) forControlEvents:UIControlEventTouchUpInside];
    [APPDELEGATE.window addSubview:_inputView];
    
    UIView* botton = [[UIView alloc] init];
    botton.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 44);
    botton.tag = 3000;
    botton.backgroundColor = WHITE;
    [_inputView addSubview:botton];
    
    UITextView* textview = [[UITextView alloc] init];
    textview.frame = CGRectMake(10, 6, SCREEN_WIDTH - 20, 32);
    textview.font = FONT_15;
    textview.tag = 3001;
    textview.textColor = BLACK;
    textview.returnKeyType = UIReturnKeySend;
    textview.layer.cornerRadius = 5;
    textview.layer.masksToBounds = YES;
    textview.backgroundColor = LINE;
    textview.delegate = self;
    textview.showsVerticalScrollIndicator = NO;
    [textview becomeFirstResponder];
    [botton addSubview:textview];
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if([text isEqualToString:@"\n"])
    {
        NSString* comment = ((UITextView*)[_inputView viewWithTag:3001]).text;
        if(comment.length == 0)
        {
            [APPDELEGATE.mMainViewController showAllTextDialog:@"请输入内容"];
            return NO;
        }
        
        NSMutableDictionary* item = [[NSMutableDictionary alloc] initWithDictionary:_mArray[_clickRow]];
        
        NSMutableDictionary* param = [[NSMutableDictionary alloc] init];
        [param setValue:APPDELEGATE.mMemberInfo[@"id"] forKey:@"id"];
        [param setValue:item[@"id"] forKey:@"post_id"];
        [param setValue:comment forKey:@"comment"];
        [self sendHttpPost:param method:@"send_post_comment" flag:7];
        
        return NO;
    }
    return YES;
}

- (void)textViewDidChange:(UITextView *)textView
{
    CGSize size = [textView sizeThatFits:CGSizeMake(CGRectGetWidth(textView.frame), MAXFLOAT)];
    if(size.height > 90) size.height = 90;
    if(size.height < 32) size.height = 32;
    
    CGRect frame = textView.frame;
    frame.size.height = size.height;
    textView.frame = frame;
    
    UIView* subview= [_inputView viewWithTag:3000];
    frame = subview.frame;
    frame.origin.y = SCREEN_HEIGHT - _keyboardHeight - (textView.frame.size.height + 12)  + 64;
    frame.size.height = textView.frame.size.height + 12;
    subview.frame = frame;
}

- (void) keyboardChange:(int)height
{
    if(_inputView)
    {
        _keyboardHeight = height;
        
        UIView* subview= [_inputView viewWithTag:3000];
        CGRect frame = subview.frame;
        frame.origin.y = SCREEN_HEIGHT - _keyboardHeight - frame.size.height + 64;
        subview.frame = frame;
    }
}

- (void) sendDataHttpPost
{
    if(![APPDELEGATE getTabInit:_mTab]) return;
    
    [APPDELEGATE setTabInit:NO tab:_mTab];
    _mGetMore = 0;
    [self sendHttpPost];
}

- (void) sendHttpPost:(NSMutableDictionary*)param method:(NSString*)method flag:(int)flag
{
    [self viewWithTag:369].hidden = YES;
    [APPDELEGATE.mMainViewController showWaitDialog];
    
    [param setValue:[Utils md5:[NSString stringWithFormat:@"%@ylbb",method]] forKey:@"sec"];
    // 初始化Manager
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    // 不加上这句话，会报“Request failed: unacceptable content-type: text/plain”错误，因为我们要获取text/plain类型数据
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    // post请求
    [manager POST:[NSString stringWithFormat:@"http://120.27.129.233/ylbb/api/%@",method]
       parameters:param constructingBodyWithBlock:^(id  _Nonnull formData) {
           // 拼接data到请求体，这个block的参数是遵守AFMultipartFormData协议的。
           
       } progress:^(NSProgress * _Nonnull uploadProgress) {
           // 这里可以获取到目前的数据请求的进度
           
       } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
           NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
           
           [APPDELEGATE.mMainViewController dissmissDialog];
           if([dic[@"statusCode"] intValue] == 0)
           {
               [self httpCallback:dic flag:flag];
           }
           else
           {
               [APPDELEGATE.mMainViewController showMsg:dic[@"message"]];
           }
       } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
           [APPDELEGATE.mMainViewController dissmissDialog];
           [APPDELEGATE.mMainViewController showAllTextDialog:@"网络状况不佳，请稍后重试..."];
           @try {
               [APPDELEGATE.mMainViewController httpCallbackFail:flag];
           } @catch (NSException *exception) {
               
           } @finally {
               
           }
       }];
}

- (BOOL) isContain:(NSArray*)array class:(NSString*)classId
{
    if([Utils isStringNullOrEmpty:classId]) return NO;
    
    for(NSString* item in array)
    {
        if([item intValue] == [[classId description] intValue])
        {
            return YES;
        }
    }
    
    return NO;
}

- (NSArray*) filterExpire:(NSArray*)array
{
    @try {
        NSMutableArray* idArr = [[NSMutableArray alloc] init];
        
        NSArray* child = APPDELEGATE.mMemberInfo[@"children"];
        NSArray* classes = APPDELEGATE.mMemberInfo[@"classes"];
        NSMutableString* str = [NSMutableString stringWithCapacity:256];
        
        for(NSDictionary* item in child)
        {
            if([self isContain:array class:item[@"class_id"]])
            {
                if(item[@"expire_date"] == nil || [[item[@"expire_date"] description] isEqualToString:@"0"])
                {
                    if(str.length) [str appendString:@","];
                    [str appendString:item[@"name"]];
                }
                else
                {
                    NSDate* date = [Utils string2Date:item[@"expire_date"] format:@"yyyy-MM-dd HH:mm:ss"];
                    if([date compare:[NSDate date]] > 0)
                    {
                        if(_mTab < 3) [idArr addObject:[item[@"class_id"] description]];
                        else [idArr addObject:[item[@"student_id"] description]];
                    }
                    else
                    {
                        if(str.length) [str appendString:@","];
                        [str appendString:item[@"name"]];
                    }
                }
            }
        }
        
        
        if(!_isWarning && str.length)
        {
            _isWarning = YES;
            [APPDELEGATE.mMainViewController showMsg:[NSString stringWithFormat:@"%@\n服务已过期，请续费",str]];
        }
        
        if(_mTab < 3)
        {
            for(NSDictionary* item in classes)
            {
                if([Utils isStringNullOrEmpty:item[@"is_teacher"]]) continue;
                
                if([item[@"is_teacher"] intValue] > 0 && [self isContain:array class:item[@"id"]]
                   && ![self isContain:idArr class:item[@"id"]])
                {
                    [idArr addObject:[item[@"id"] description]];
                }
            }
        }
        
        return idArr;
    } @catch (NSException *exception) {
        
    } @finally {
        
    }
    
    return nil;
}

- (void) sendHttpPost
{
    if(_mArray.count == 0)
    {
        [self.mj_header performSelector:@selector(beginRefreshing) withObject:nil afterDelay:0.1];
        return;
    }
    
    [self viewWithTag:369].hidden = YES;
    
    NSMutableDictionary* param = [[NSMutableDictionary alloc] init];
    [param setValue:APPDELEGATE.mMemberInfo[@"id"] forKey:@"id"];
    
    if(_mTab == 0)
    {
        [param setValue:[APPDELEGATE.mMainViewController.mSelectClass componentsJoinedByString:@","] forKey:@"class_id"];
        [param setValue:@"4" forKey:@"type"];
    }
    else if(_mTab == 1)
    {
//        NSArray* array = [self filterExpire:_mMainViewController.mSelectClass];
        //        [param setValue:[array componentsJoinedByString:@","] forKey:@"class_id"];
        [param setValue:[APPDELEGATE.mMainViewController.mSelectClass componentsJoinedByString:@","] forKey:@"class_id"];
        [param setValue:@"1" forKey:@"type"];
    }
    else if(_mTab == 2)
    {
//        NSArray* array = [self filterExpire:_mMainViewController.mSelectClass];
//        if(array.count) return;
        //        [param setValue:[array componentsJoinedByString:@","] forKey:@"class_id"];
        [param setValue:[APPDELEGATE.mMainViewController.mSelectClass componentsJoinedByString:@","] forKey:@"class_id"];
        [param setValue:@"2" forKey:@"type"];
    }
    else if(_mTab == 3)
    {
//        NSArray* array = [self filterExpire:_mMainViewController.mSelectClass];
//        [param setValue:[array componentsJoinedByString:@","] forKey:@"student_id"];
//        
        [param setValue:[APPDELEGATE.mMainViewController.mSelectClass componentsJoinedByString:@","] forKey:@"class_id"];
        [param setValue:@"5" forKey:@"type"];
    }

    int count = (int)_mArray.count;
    if(_mGetMore == 1)
    {
        [param setValue:[NSNumber numberWithInt:count] forKey:@"start"];
        [param setValue:[NSNumber numberWithInt:10] forKey:@"perpage"];
    }
    else
    {
        int count = (int)_mArray.count;
        if(count < 10) count = 10;
        
        [param setValue:@"0" forKey:@"start"];
        [param setValue:[NSNumber numberWithInt:count] forKey:@"perpage"];
    }
    
    if(_mGetMore == 2) [self sendHttpPost:param method:@"get_post_list" flag:_mTab];
    else [self sendHttpPostNOWait:param method:@"get_post_list" flag:_mTab];
}

- (void) sendHttpPostNOWait:(NSMutableDictionary*)param method:(NSString*)method flag:(int)flag
{
    [self viewWithTag:369].hidden = YES;
    
    [param setValue:[Utils md5:[NSString stringWithFormat:@"%@ylbb",method]] forKey:@"sec"];
    // 初始化Manager
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    // 不加上这句话，会报“Request failed: unacceptable content-type: text/plain”错误，因为我们要获取text/plain类型数据
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    // post请求
    [manager POST:[NSString stringWithFormat:@"http://120.27.129.233/ylbb/api/%@",method]
       parameters:param constructingBodyWithBlock:^(id  _Nonnull formData) {
           // 拼接data到请求体，这个block的参数是遵守AFMultipartFormData协议的。
           
       } progress:^(NSProgress * _Nonnull uploadProgress) {
           // 这里可以获取到目前的数据请求的进度
           
       } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
           NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
           if([NSStringFromClass(dic.class) containsString:@"NSArray"] || [dic[@"statusCode"] intValue] == 0)
           {
               [self httpCallback:dic flag:flag];
           }
           else
           {
               [APPDELEGATE.mMainViewController showMsg:dic[@"message"]];
           }
       } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
           @try {
               [self httpCallbackFail:flag];
           } @catch (NSException *exception) {
               
           } @finally {
               
           }
       }];
}

- (void) refreshList:(NSDictionary*)data
{
    [self reloadData];
    [APPDELEGATE.mMainViewController setRed:data[@"badge"]];
    _mGetMore = 0;
    
    [self performSelector:@selector(endRefresh) withObject:nil afterDelay:0.1];
}

- (void) endRefresh
{
    [self.mj_header endRefreshing];
    [self.mj_footer endRefreshing];
    
    [self viewWithTag:369].hidden = YES;
    if(_mArray.count == 0) [self viewWithTag:369].hidden = NO;
}

- (void) tackleData:(NSDictionary*)data
{
    int i = 0;
    if(_mGetMore == 1)
    {
        i = (int)_mArray.count;
        [_mArray addObjectsFromArray:data[@"datalist"]];
    }
    else [_mArray setArray:data[@"datalist"]];
    
    for(; i < _mArray.count; i++)
    {
        NSDictionary* item = _mArray[i];
        
        NSMutableString* praiseStr = [[NSMutableString alloc] init];
        NSMutableString* commentStr = [[NSMutableString alloc] init];
        
        NSArray* praise = item[@"praise"];
        NSArray* comment = item[@"comment"];
        
        if(praise && [NSStringFromClass(praise.class) containsString:@"NSArray"] && praise.count)
        {
            for(NSDictionary* index in praise)
            {
                NSString* username = index[@"alias"];
                if([[index[@"member_id"] description] isEqualToString:[APPDELEGATE.mMemberInfo[@"id"] description]]) username = @"我";
                else if([Utils isStringNullOrEmpty:username]) username = index[@"username"];
                if(![Utils isStringNullOrEmpty:username])
                {
                    if(praiseStr.length) [praiseStr appendString:@"，"];
                    [praiseStr appendString:username];
                }
            }
        }
        
        if(comment && [NSStringFromClass(comment.class) containsString:@"NSArray"] && comment.count)
        {
            for(NSDictionary* index in comment)
            {
                NSString* username = index[@"alias"];
                if([[index[@"member_id"] description] isEqualToString:[APPDELEGATE.mMemberInfo[@"id"] description]]) username = @"我";
                else if([Utils isStringNullOrEmpty:username]) username = index[@"username"];
                if(![Utils isStringNullOrEmpty:username])
                {
                    if(commentStr.length) [commentStr appendString:@"\n"];
                    [commentStr appendString:username];
                    [commentStr appendString:@": "];
                    [commentStr appendString:index[@"comment"]];
                }
            }
        }
        
        NSMutableDictionary* modify = [[NSMutableDictionary alloc] initWithDictionary:item];
        [modify setValue:praiseStr forKey:@"praiseStr"];
        [modify setValue:commentStr forKey:@"commentStr"];
        [_mArray replaceObjectAtIndex:i withObject:modify];
    }
    
    [self performSelectorOnMainThread:@selector(refreshList:) withObject:data waitUntilDone:YES];
}

- (void) httpCallback:(NSDictionary*)data flag:(int)flag
{
    if(flag == 0)
    {
        [NSThread detachNewThreadSelector:@selector(tackleData:) toTarget:self withObject:data];
    }
    else if(flag == 1 || flag == 2 || flag == 3)
    {
        if(_mGetMore == 1) [_mArray addObjectsFromArray:data[@"datalist"]];
        else [_mArray setArray:data[@"datalist"]];
        [self reloadData];
        _mGetMore = 0;
        [APPDELEGATE.mMainViewController setRed:data[@"badge"]];
        
        [self performSelector:@selector(endRefresh) withObject:nil afterDelay:0.1];
    }
    else if(flag == 5)
    {
        
    }
    else if(flag == 6)
    {
        _mGetMore = 2;
        [self sendHttpPost];
    }
    else if(flag == 7)
    {
        [self removeSelf];
        
        _mGetMore = 2;
        [self sendHttpPost];
    }
}

- (void) commandClick:(UIButton*)btn
{
    _clickRow = [[btn titleForState:UIControlStateDisabled] intValue];
    NSDictionary* item = _mArray[_clickRow];
    if(btn.tag == 2115)
    {
        NSMutableDictionary* param = [[NSMutableDictionary alloc] init];
        [param setValue:APPDELEGATE.mMemberInfo[@"id"] forKey:@"id"];
        [param setValue:item[@"id"] forKey:@"post_id"];
        [self sendHttpPostNOWait:param method:@"send_post_praise" flag:5];
        
        NSMutableDictionary* item = _mArray[_clickRow];
        NSMutableString* array = item[@"praiseStr"];
        if(array.length) [array appendString:@"，"];
        [array appendString:@"我"];
        
        NSMutableDictionary* praise = [[NSMutableDictionary alloc] init];
        [praise setValue:APPDELEGATE.mMemberInfo[@"id"] forKey:@"member_id"];
        [item setValue:@"1" forKey:@"is_praised"];
        [item setValue:array forKey:@"praise"];
        [self reloadData];
    }
    else
    {
        if(_mTab == 0)
        {
            [self showCommentDialog];
        }
        else if([item[@"receipt"] intValue] == 1 && [item[@"is_feedbacked"] intValue] == 0)
        {
            NSMutableDictionary* param = [[NSMutableDictionary alloc] init];
            [param setValue:APPDELEGATE.mMemberInfo[@"id"] forKey:@"id"];
            [param setValue:item[@"id"] forKey:@"post_id"];
            [self sendHttpPost:param method:@"send_post_feedback" flag:6];
        }
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _mArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView  dequeueReusableCellWithIdentifier:@"cell"];
    
    if(cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        cell.backgroundColor = WHITE;
        
        UIView* subview = cell;
 /*       subview.frame = CGRectMake(0, 0, SCREEN_WIDTH, 0);
        subview.tag = 2100;
        subview.layer.cornerRadius = 5;
        subview.layer.masksToBounds = YES;
        subview.backgroundColor = WHITE;
        [cell addSubview:subview];
        */
        CALayer* layer = [[CALayer alloc] init];
        layer.frame = CGRectMake(0, 0, SCREEN_WIDTH, .5);
        layer.backgroundColor = kUIColorFromRGB(0xDADADA).CGColor;
        [subview.layer addSublayer:layer];
        
        UIButton* imageview = [UIButton buttonWithType:UIButtonTypeCustom];
        imageview.frame = CGRectMake(10, 10, 36, 36);
        imageview.contentMode = UIViewContentModeScaleAspectFill;
        imageview.layer.cornerRadius = 18;
        imageview.layer.masksToBounds = YES;
        imageview.tag = 2101;
        [imageview addTarget:self action:@selector(iconClick:) forControlEvents:UIControlEventTouchUpInside];
        [subview addSubview:imageview];
        
        UILabel* label = [[UILabel alloc] init];
        label.frame = CGRectMake(56, 10, SCREEN_WIDTH - 84, 20);
        label.font = [UIFont fontWithName:@"Helvetica-Bold" size:15];
        label.textColor = BLUE;
        label.tag = 2102;
        [subview addSubview:label];
        
        label = [[UILabel alloc] init];
        label.font = FONT_10;
        label.frame = CGRectMake(100, 12, 32, 16);
        label.textColor = WHITE;
        label.tag = 3003;
        label.text = @"老师";
        label.hidden = YES;
        label.textAlignment = NSTextAlignmentCenter;
        label.backgroundColor = ORANGE;
        label.layer.cornerRadius = 3;
        label.layer.masksToBounds = YES;
        [subview addSubview:label];
        
        UIButton* btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(SCREEN_WIDTH - 45, 15, 40, 20);
        btn.tag = 2200;
        btn.enabled = NO;
        btn.titleEdgeInsets = UIEdgeInsetsMake(-5, 0, 0, 0);
        btn.titleLabel.font = FONT_10;
        [btn setTitleColor:WHITE forState:UIControlStateDisabled];
        [btn setBackgroundImage:[UIImage imageNamed:@"label_s"] forState:UIControlStateDisabled];
        [cell addSubview:btn];
        
        label = [[UILabel alloc] init];
        label.frame = CGRectMake(56, 30, SCREEN_WIDTH - 84, 20);
        label.font = FONT_13;
        label.textColor = ORANGE;
        label.tag = 2103;
        label.numberOfLines = 0;
        label.lineBreakMode = NSLineBreakByCharWrapping;
        [subview addSubview:label];
        
        label = [[UILabel alloc] init];
        label.frame = CGRectMake(56, 60, SCREEN_WIDTH - 84, 20);
        label.font = FONT_14;
        label.textColor = BLACK;
        label.tag = 2104;
        label.numberOfLines = 0;
        label.lineBreakMode = NSLineBreakByCharWrapping;
        [subview addSubview:label];
        
        for(int i = 0; i < 9; i++)
        {
            UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.tag = 2105 + i;
            button.layer.masksToBounds = YES;
            [button addTarget:self action:@selector(imageviewClick:) forControlEvents:UIControlEventTouchUpInside];
            button.contentMode = UIViewContentModeScaleAspectFill;
            
            UIImageView* icon = [[UIImageView alloc] init];
            icon.tag = 1234;
            icon.contentMode =  UIViewContentModeScaleAspectFill ;
            [button addSubview:icon];
            
            [subview addSubview:button];
        }
        
        label = [[UILabel alloc] init];
        label.frame = CGRectMake(56, 60, 240, 20);
        label.font = FONT_12;
        label.textColor = LINE;
        label.tag = 2114;
        [subview addSubview:label];
        
        for(int i = 0; i < 3; i++)
        {
            UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
            if(i == 2) button.tag = 3000 + i;
            else button.tag = 2115 + i;
            button.titleLabel.font = FONT_10;
            [button setBackgroundImage:[Utils imageFromColor:kUIColorFromRGB(0x78A9E5)] forState:UIControlStateNormal];
            [button setTitleColor:WHITE forState:UIControlStateNormal];
            if(i == 0)
            {
                [button setTitle:@" 赞" forState:UIControlStateNormal];
                [button setImage:[UIImage imageNamed:@"ic_good"] forState:UIControlStateNormal];
            }
            if(i == 1)
            {
                [button setImage:[UIImage imageNamed:@"ic_comment"] forState:UIControlStateNormal];
                [button setTitle:@" 评论" forState:UIControlStateNormal];
            }
            if(i == 2)
            {
                [button setImage:[UIImage imageNamed:@"ic_feed"] forState:UIControlStateNormal];
                [button setTitle:@" 我知道了" forState:UIControlStateNormal];
            }
            [button addTarget:self action:@selector(commandClick:) forControlEvents:UIControlEventTouchUpInside];
            [subview addSubview:button];
        }
        
        UIImageView* imagev = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"arrow"]];
        imagev.tag = 2117;
        [subview addSubview:imagev];
        
        UIView* top = [[UIView alloc] init];
        top.tag = 2118;
        top.backgroundColor = kUIColorFromRGB(0xF3F3F5);
        [subview addSubview:top];
        
        imagev = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon_like"]];
        imagev.tag = 2119;
        imagev.frame = CGRectMake(5, 8, 15, 15);
        [top addSubview:imagev];
        
        label = [[UILabel alloc] init];
        label.tag = 2120;
        label.textColor = BLUE;
        label.numberOfLines = 0;
        label.lineBreakMode = NSLineBreakByCharWrapping;
        label.font = FONT_12;
        [top addSubview:label];
        
        top = [[UIView alloc] init];
        top.tag = 2121;
        top.backgroundColor = kUIColorFromRGB(0xF3F3F5);
        [subview addSubview:top];
        
        layer = [[CALayer alloc] init];
        layer.frame = CGRectMake(0, 0, SCREEN_WIDTH - 66, .5);
        layer.backgroundColor = kUIColorFromRGB(0xDDDCE1).CGColor;
        [top.layer addSublayer:layer];
        
        label = [[UILabel alloc] init];
        label.tag = 2122;
        label.textColor = BLACK;
        label.numberOfLines = 0;
        label.lineBreakMode = NSLineBreakByCharWrapping;
        label.font = FONT_12;
        [top addSubview:label];
    }
    
    int pos = (int)indexPath.row;
    NSDictionary* item = _mArray[pos];

    UIView* subview = cell;
    UIButton* icon = (UIButton*)[subview viewWithTag:2101];
    UILabel* titleLabel = (UILabel*)[subview viewWithTag:2102];
    UILabel* signLabel = (UILabel*)[subview viewWithTag:3003];
    UILabel* classLabel = (UILabel*)[subview viewWithTag:2103];
    UILabel* contentLabel = (UILabel*)[subview viewWithTag:2104];
    UILabel* timeLabel = (UILabel*)[subview viewWithTag:2114];
    UIButton* leftBtn = (UIButton*)[subview viewWithTag:2115];
    UIButton* rightBtn = (UIButton*)[subview viewWithTag:2116];
    UIButton* feedBtn = (UIButton*)[subview viewWithTag:3002];
    UIImageView* arrow = (UIImageView*)[subview viewWithTag:2117];
    UIView* top = [subview viewWithTag:2118];
    UILabel* praiseLabel = (UILabel*)[subview viewWithTag:2120];
    UIView* bottom = [subview viewWithTag:2121];
    UILabel* commentLabel = (UILabel*)[subview viewWithTag:2122];
    UIButton* btn = (UIButton*)[cell viewWithTag:2200];
    
    btn.hidden = YES;
    if(_mTab == 0) [btn setTitle:@"动态" forState:UIControlStateDisabled];
    if(_mTab == 1) [btn setTitle:@"作业" forState:UIControlStateDisabled];
    if(_mTab == 2) [btn setTitle:@"通知" forState:UIControlStateDisabled];
    if(_mTab == 3)
    {
        int tour = [item[@"isinout"] intValue];
        if(tour == 1) [btn setTitle:@"入校" forState:UIControlStateDisabled];
        else if(tour == 2) [btn setTitle:@"离校" forState:UIControlStateDisabled];
        else btn.hidden = YES;
    }
    
    /*
     "card_id" = 1241993901;
     "class_name" = "2015\U5e74\U5c0f1\U5e74\U7ea7\U77ed\U4fe1\U7248";
     dateline = "2016-06-17 10:23:38";
     datetime = "2016-06-17 10:24:07";
     id = 3888;
     maxid = 297E2F04555C28A001555C2BBFC80004;
     name = "\U5468\U90ce";
     status = 0;
     */
    [icon setTitle:[NSString stringWithFormat:@"%d",(int)indexPath.row] forState:UIControlStateDisabled];
    if(_mTab == 3)
    {
        [icon setImage:[UIImage imageNamed:@"AppIcon60x60"] forState:UIControlStateNormal];
    }
    else{
        if([item[@"is_teacher"] intValue] == 0)
            [icon setImageForState:UIControlStateNormal withURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IMG_URL,item[@"avatar_path"]]]
                  placeholderImage:[UIImage imageNamed:@"ic_family"]];
        else
            [icon setImageForState:UIControlStateNormal withURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IMG_URL,item[@"avatar_path"]]]
                  placeholderImage:[UIImage imageNamed:@"ic_teacher"]];
    }
    
    NSString* username = item[@"creator_alias"];
    if([[item[@"creator"] description] isEqualToString:[APPDELEGATE.mMemberInfo[@"id"] description]]) username = @"我";
    else if([Utils isStringNullOrEmpty:username]) username = item[@"creator_name"];
    if(_mTab == 3) username = @"月亮巴巴";
    titleLabel.text = username;
    
    signLabel.hidden = YES;
    if([item[@"is_teacher"] intValue] == 1)
    {
        int width = [titleLabel sizeThatFits:CGSizeMake(160, 20)].width + 5;
        signLabel.hidden = NO;
        signLabel.frame = CGRectMake(56 + width, 12, 32, 16);
    }
    
    NSString* className = item[@"class_name_alias"];
    if([Utils isStringNullOrEmpty:className]) className = item[@"class_name"];
    if([Utils isStringNullOrEmpty:className]) className = @"";
    
    classLabel.text = className;
    int heigt = [classLabel sizeThatFits:CGSizeMake(SCREEN_WIDTH - 84, 1000)].height;
    int yPos = 50;
    if(heigt < 20) classLabel.frame = CGRectMake(56, 30, SCREEN_WIDTH - 84, 20);
    else
    {
        classLabel.frame = CGRectMake(56, 30, SCREEN_WIDTH - 84, heigt + 8);
        yPos += (heigt + 8 - 20);
    }
    
    contentLabel.text = item[@"content"];
    
    heigt = [contentLabel sizeThatFits:CGSizeMake(SCREEN_WIDTH - 66, 1000)].height + 8;
    contentLabel.frame = CGRectMake(56, yPos, SCREEN_WIDTH - 66, heigt);
    
    yPos += heigt + 5;
    NSString* attach_list = [item[@"attach_list"] description];
    if([Utils isStringNullOrEmpty:attach_list]) attach_list = @"";
    NSArray* array = [attach_list componentsSeparatedByString:NSLocalizedString(@",", nil)];
    int width = (SCREEN_WIDTH - 76)/3;
    for(int i = 0; i < 9; i++)
    {
        UIButton* button = (UIButton*)[subview viewWithTag:2105 + i];
        [button setTitle:[NSString stringWithFormat:@"%d",(int)indexPath.row] forState:UIControlStateDisabled];
        if (i < array.count && attach_list.length > 0)
        {
            UIImageView* icon = (UIImageView*)[button viewWithTag:1234];
            button.hidden = NO;
            icon.frame = CGRectMake(0, 0, width, width);
            [icon setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@&width=%d&height=%d",IMG_URL_0,array[i],160,160]]
                    placeholderImage:IMG_DEFAULT];
            button.frame = CGRectMake((i%3)*(width + 5) + 56, yPos + (i/3)*(width + 5), width, width);
        }
        else
        {
            button.hidden = YES;
        }
    }
    
    if(array && array.count && attach_list.length)
    {
        if(array.count < 4) yPos += (width + 5);
        else if(array.count < 7 && array.count > 3) yPos += 2*(width + 5);
        else if(array.count > 6) yPos += 3*(width + 10);
    }
    
    timeLabel.frame = CGRectMake(56, yPos, 160, 20);
    timeLabel.text = [Utils date2format:item[@"created_at"]];
    if(_mTab == 3)
    {
        NSDate* date = [Utils string2Date:item[@"dateline"] format:@"yyyy-MM-dd HH:mm:ss"];
        timeLabel.text = [Utils date2String:date format:@"yyyy-MM-dd"];
    }
    
    leftBtn.hidden = YES;
    if(_mTab == 0 && [item[@"is_praised"] intValue] == 0)
    {
        [leftBtn setTitle:[NSString stringWithFormat:@"%d",(int)indexPath.row] forState:UIControlStateDisabled];
        leftBtn.frame = CGRectMake((SCREEN_WIDTH - 86), yPos, 36, 24);
        leftBtn.hidden = NO;
    }
    
    rightBtn.hidden = YES;
    if(_mTab == 0)
    {
        [rightBtn setTitle:[NSString stringWithFormat:@"%d",(int)indexPath.row] forState:UIControlStateDisabled];
        rightBtn.frame = CGRectMake((SCREEN_WIDTH - 50), yPos, 40, 24);
        rightBtn.hidden = NO;
    }

    
    feedBtn.hidden = YES;
    if(_mTab > 0 && [item[@"receipt"] intValue] == 1 && [item[@"is_feedbacked"] intValue] == 0)
    {
        [feedBtn setTitle:[NSString stringWithFormat:@"%d",(int)indexPath.row] forState:UIControlStateDisabled];
        feedBtn.frame = CGRectMake((SCREEN_WIDTH - 70), yPos, 60, 24);
        feedBtn.hidden = NO;
    }
    
    yPos += 20;
    
    NSString* praise = item[@"praiseStr"];
    NSString* comment = item[@"commentStr"];
    
    arrow.hidden = YES;
    if((praise && praise.length) || (comment && comment.length))
    {
        yPos += 5;
        arrow.hidden = NO;
        arrow.frame = CGRectMake(64, yPos, 10, 6);
        yPos += 6;
    }
    
    top.hidden = YES;
    if(praise && praise.length)
    {
        top.hidden = NO;
        praiseLabel.text = praise;
        int heigt = [praiseLabel sizeThatFits:CGSizeMake(SCREEN_WIDTH - 100, 1000)].height + 16;
        praiseLabel.frame = CGRectMake(24, 0, SCREEN_WIDTH - 100, heigt);
        top.frame = CGRectMake(56, yPos, SCREEN_WIDTH - 66, heigt);
        
        yPos += heigt;
    }
    
    bottom.hidden = YES;
    if(comment && comment.length)
    {
        bottom.hidden = NO;
        
        commentLabel.text = comment;
        int heigt = [commentLabel sizeThatFits:CGSizeMake(SCREEN_WIDTH - 72, 1000)].height + 16;
        commentLabel.frame = CGRectMake(5, 0, SCREEN_WIDTH - 72, heigt);
        bottom.frame = CGRectMake(56, yPos, SCREEN_WIDTH - 66, heigt);
        
        yPos += heigt;
    }
    
//    subview.frame = CGRectMake(10, 10, SCREEN_WIDTH - 20, yPos + 10);
    @try {
        cell.frame = CGRectMake(0, 0, SCREEN_WIDTH, yPos);
    } @catch (NSException *exception) {
        
    } @finally {
        
    }
    
    [_mHeightDic setValue:[NSNumber numberWithInt:yPos + 20] forKey:[NSString stringWithFormat:@"%d",(int)indexPath.row]];
    
    return cell;
}

- (void) iconClick:(UIButton*)btn
{
    if(3 == _mTab) return;
    
    int index = [[btn titleForState:UIControlStateDisabled] intValue];
    NSDictionary* item = _mArray[index];
    MateInfoViewController* subview = [[MateInfoViewController alloc] init];
    subview.mUserId = [item[@"creator"] description];
    subview.hidesBottomBarWhenPushed = YES;
    [APPDELEGATE.mMainViewController.navigationController pushViewController:subview animated:YES];
}

- (void) imageviewClick:(UIButton*)btn
{
    UIView* cell = [btn superview];
    NSMutableArray* imgArray = [[NSMutableArray alloc] init];
    
    int index = [[btn titleForState:UIControlStateDisabled] intValue];
    NSDictionary* item = _mArray[index];
    NSString* attach_list = item[@"attach_list"];
    NSMutableArray* array = [[NSMutableArray alloc] initWithArray:[attach_list componentsSeparatedByString:NSLocalizedString(@",", nil)]];
    
    for(int i = 0; i < array.count; i++)
    {
        [array replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%@%@&width=640&height=640",IMG_URL_0,array[i]]];
        
        UIImageView* imageview = (UIImageView*)[[cell viewWithTag:2105 + i] viewWithTag:1234];
        [imgArray addObject:imageview.image];
    }

    ImageShowViewController* subview = [[ImageShowViewController alloc] init];
    subview.hidesBottomBarWhenPushed = YES;
    subview.imgArr = array;
    subview.imageArray = imgArray;
    subview.currentIndex = btn.tag - 2105;
    [APPDELEGATE.mMainViewController.navigationController pushViewController:subview animated:YES];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(_mArray.count <= indexPath.row) return 0;

    NSString* key = [NSString stringWithFormat:@"%d",(int)indexPath.row];
    if(!_mHeightDic[key]) return 0;
    
    return [_mHeightDic[key] intValue];
}
@end
